package com.homework.handler;


import com.homework.pojo.Result;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.HttpRequest;
import org.springframework.http.HttpStatus;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * 全局异常处理器，处理项目中抛出的业务异常
 */
@RestControllerAdvice
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler({DuplicateKeyException.class, DataIntegrityViolationException.class})
    public Result handleDuplicateKeyException(Exception ex) {
        String message = ex.getCause() != null ? ex.getCause().getMessage() : ex.getMessage();
        log.error("异常信息：{}", ex.getMessage());
        if (message != null && message.contains("Duplicate entry")) {
            String duplicateValue = message.split(" ")[2];
            return Result.error(duplicateValue + "已存在");
        }
        return Result.error("数据库唯一约束冲突！");
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handleValidException(MethodArgumentNotValidException ex) {
        // 获取所有字段的错误信息
        List<FieldError> fieldErrors = ex.getBindingResult().getFieldErrors();
        StringBuilder errorMessages = new StringBuilder("参数错误：");
        for (FieldError error : fieldErrors) {
            errorMessages.append(error.getField())
                    .append(": ")
                    .append(error.getDefaultMessage())
                    .append("; ");
        }
        // 打印详细的错误日志
        log.error(errorMessages.toString());
        return Result.error(errorMessages.toString());
    }


    @ExceptionHandler(Exception.class)
    public Result exceptionHandler(Exception ex, HttpServletRequest httpServletRequest) {
        log.error("请求路径: {}", httpServletRequest.getRequestURI()); // 记录完整异常堆栈
        log.error("异常信息：{}", ex.getMessage());
        return Result.error(ex.getMessage());
    }

}
